import { useState } from 'react';
import { 
    Box, 
    Button, 
    Typography, 
    Paper,
    Grid,
    TextField,
    FormControl,
    InputLabel,
    Select,
    MenuItem,
    IconButton,
    Tooltip
} from '@mui/material';
import ToolPageTemplate from '@/components/ToolPageTemplate';
import SecurityIcon from '@mui/icons-material/Security';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';

const MD5HashPage = () => {
    const [input, setInput] = useState('');
    const [algorithm, setAlgorithm] = useState('MD5');
    const [result, setResult] = useState('');

    const calculateHash = async () => {
        if (!input.trim()) return;

        try {
            const encoder = new TextEncoder();
            const data = encoder.encode(input);
            
            let hashBuffer: ArrayBuffer;
            
            switch (algorithm) {
                case 'SHA-1':
                    hashBuffer = await crypto.subtle.digest('SHA-1', data);
                    break;
                case 'SHA-256':
                    hashBuffer = await crypto.subtle.digest('SHA-256', data);
                    break;
                case 'SHA-384':
                    hashBuffer = await crypto.subtle.digest('SHA-384', data);
                    break;
                case 'SHA-512':
                    hashBuffer = await crypto.subtle.digest('SHA-512', data);
                    break;
                default:
                    // MD5 需要额外实现或使用库
                    setResult('MD5算法需要引入额外库实现');
                    return;
            }
            
            const hashArray = Array.from(new Uint8Array(hashBuffer));
            const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
            setResult(hashHex);
        } catch (error) {
            setResult('计算失败');
        }
    };

    const copyToClipboard = () => {
        if (result) {
            navigator.clipboard.writeText(result);
        }
    };

    const loadExample = () => {
        setInput('Hello, World! 这是一个哈希计算示例。');
        setResult('');
    };

    return (
        <ToolPageTemplate 
            title="哈希计算器"
            description="计算文本的MD5、SHA等哈希值"
            category="安全工具"
            categoryColor="#d32f2f"
        >
            <Grid container spacing={4}>
                <Grid item xs={12} md={6}>
                    <Box sx={{ 
                        display: 'flex', 
                        justifyContent: 'space-between', 
                        alignItems: 'center',
                        mb: 2 
                    }}>
                        <Typography variant="h6" sx={{ fontWeight: 600 }}>
                            输入文本
                        </Typography>
                        <Button
                            variant="text"
                            size="small"
                            startIcon={<AutoFixHighIcon />}
                            onClick={loadExample}
                            sx={{ 
                                textTransform: 'none',
                                fontWeight: 600,
                                color: 'primary.main',
                                '&:hover': {
                                    bgcolor: 'primary.main',
                                    color: 'primary.contrastText'
                                }
                            }}
                        >
                            加载示例
                        </Button>
                    </Box>
                    <TextField
                        fullWidth
                        multiline
                        rows={6}
                        placeholder="请输入要计算哈希值的文本..."
                        value={input}
                        onChange={(e) => setInput(e.target.value)}
                        sx={{ mb: 3 }}
                    />
                    
                    <FormControl fullWidth sx={{ mb: 3 }}>
                        <InputLabel>哈希算法</InputLabel>
                        <Select
                            value={algorithm}
                            label="哈希算法"
                            onChange={(e) => setAlgorithm(e.target.value)}
                        >
                            <MenuItem value="MD5">MD5</MenuItem>
                            <MenuItem value="SHA-1">SHA-1</MenuItem>
                            <MenuItem value="SHA-256">SHA-256</MenuItem>
                            <MenuItem value="SHA-384">SHA-384</MenuItem>
                            <MenuItem value="SHA-512">SHA-512</MenuItem>
                        </Select>
                    </FormControl>

                    <Button 
                        variant="contained" 
                        size="large"
                        startIcon={<SecurityIcon />}
                        onClick={calculateHash}
                        disabled={!input.trim()}
                        fullWidth
                    >
                        计算哈希值
                    </Button>
                </Grid>

                <Grid item xs={12} md={6}>
                    <Typography variant="h6" sx={{ mb: 2, fontWeight: 600 }}>
                        哈希结果
                    </Typography>
                    
                    {result ? (
                        <Paper 
                            elevation={0}
                            sx={{ 
                                p: 3, 
                                bgcolor: 'grey.50',
                                border: '1px solid',
                                borderColor: 'grey.300',
                                position: 'relative'
                            }}
                        >
                            <Typography 
                                variant="body2" 
                                color="text.secondary"
                                sx={{ mb: 1 }}
                            >
                                {algorithm} 哈希值:
                            </Typography>
                            <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1 }}>
                                <Typography 
                                    component="code"
                                    sx={{ 
                                        fontFamily: 'monospace',
                                        wordBreak: 'break-all',
                                        flex: 1,
                                        bgcolor: 'white',
                                        p: 2,
                                        borderRadius: 1,
                                        border: '1px solid',
                                        borderColor: 'grey.200'
                                    }}
                                >
                                    {result}
                                </Typography>
                                <Tooltip title="复制哈希值">
                                    <IconButton onClick={copyToClipboard}>
                                        <ContentCopyIcon />
                                    </IconButton>
                                </Tooltip>
                            </Box>
                        </Paper>
                    ) : (
                        <Paper 
                            elevation={0}
                            sx={{ 
                                p: 4, 
                                textAlign: 'center',
                                bgcolor: 'grey.50',
                                minHeight: 200,
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                border: '2px dashed',
                                borderColor: 'grey.300'
                            }}
                        >
                            <Box>
                                <SecurityIcon sx={{ fontSize: 60, color: 'grey.400', mb: 2 }} />
                                <Typography variant="body1" color="text.secondary">
                                    输入文本并选择算法计算哈希值
                                </Typography>
                            </Box>
                        </Paper>
                    )}
                </Grid>
            </Grid>
        </ToolPageTemplate>
    );
};

export default MD5HashPage;